package frequency

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
	"github.com/pkg/errors"
	"talent.com/agency_im/conf/g"
)

// Redis实现
// 直接使用Redis的expire机制
type RedisLimiter struct {
	rules map[string]LimiterRule
}

func (r *RedisLimiter) RegisterRules(rules map[string]LimiterRule) error {
	r.rules = rules
	return nil
}

func (r *RedisLimiter) Check(ruleCode string, key interface{}) (bool, error) {
	var (
		//rule LimiterRule
		gKey = fmt.Sprintf("%v-%v", ruleCode, key)
	)
	if rule, ok := r.rules[ruleCode]; !ok {
		return false, errors.Errorf("the ruleCode is not exists: [%v]", ruleCode)
	} else {
		rd := g.RedisPool.Get()
		defer rd.Close()

		timers, _ := redis.Int(rd.Do("GET", gKey))

		if timers != 0 {
			if uint(timers) < rule.Count {
				timers, _ := redis.Int(rd.Do("INCR", gKey))
				if timers == 1 {
					redis.Int(rd.Do("EXPIRE", gKey, rule.Period))
				}
			}

		} else {
			rd.Do("SET", gKey, 1, "EX", rule.Period)
		}

		if uint(timers) < rule.Count {
			return true, nil
		}
	}
	return false, nil
}
